<template>
  <div class="chat-app">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <div class="logo" @click="router.push('/LifePerson')"><span>LifeCircle Chat</span></div>
      <div class="user-info">
        <div
          class="avatar"
          :style="{
            backgroundImage: `url(${currentUser.avatar ?? defaultAvatar})`,
          }"
        ></div>
        <span>{{ currentUser.name }}</span>
      </div>
    </header>

    <div class="main-content">
      <!-- 好友列表 -->
      <div class="sidebar">
        <div class="search-box">
          <input v-model="searchQuery" placeholder="搜索好友..." />
        </div>

        <div class="friends-list">
          <div
            v-for="friend in filteredFriends"
            :key="friend.userId"
            class="friend-item"
            :class="{ active: selectedFriend?.userId === friend.userId }"
            @click="selectFriend(friend)"
          >
            <div
              class="avatar"
              :style="{
                backgroundImage: `url(${friend.avatar ?? defaultAvatar})`,
              }"
            >
              <span v-if="friend.online" class="online-dot"></span>
            </div>
            <div class="friend-info">
              <div class="name">{{ friend.name }}</div>
              <div class="last-message" v-if="friend.lastMessage">
                <!-- <span class="time">{{
                  formatTime(friend.lastMessage.timestamp)
                }}</span> -->
              </div>
            </div>
            <div class="unread-count" v-if="friend.unreadCount > 0">
              {{ friend.unreadCount }}
            </div>
          </div>
        </div>
      </div>

      <!-- 聊天窗口 -->
      <div class="chat-window" v-if="selectedFriend">
        <div class="chat-header">
          <!-- <div class="back-btn" @click="selectedFriend = null"> -->
          <div class="back-btn">
            <svg width="24" height="24" viewBox="0 0 24 24">
              <path
                d="M15 19L9 12L15 5"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </div>
          <div
            class="avatar"
            :style="{ backgroundImage: `url(${selectedFriend.avatar ?? defaultAvatar})` }"
          >
            <!-- <span v-if="selectedFriend.online" class="online-dot"></span> -->
          </div>
          <div class="friend-info">
            <div class="name">{{ selectedFriend.name }}</div>
            <!-- <div class="status" v-if="selectedFriend.online">在线</div> -->
          </div>
        </div>

        <div class="messages-container" ref="messagesContainer">
          <div class="message-list">
            <div
              v-for="msg in messages"
              :key="msg.id"
              class="message"
              :class="{
                incoming: msg.publisherId !== currentUser.id,
                outgoing: msg.publisherId === currentUser.id,
              }"
            >
              <div class="message-content">
                <div class="content">{{ msg.content }}</div>
                <div class="time">{{ msg.time }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="input-area">
          <input
            v-model="messageInput"
            @keyup.enter="sendMessage"
            placeholder="输入消息..."
          />
          <button @click="sendMessage">发送</button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <div class="empty-icon">💬</div>
        <p>选择一个好友开始聊天</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
// import { format } from "date-fns";
import { getFollowedList, findUserInfoByUserId, getChat } from "@/api/life.js";
import router from "@/router";

//默认头像
const defaultAvatar = "https://picsum.photos/200/200";
// 当前用户信息
const currentUser = ref({
  id: "",
  name: "",
  avatar: "",
});
// 好友列表
let friends = ref([]);
// 当前选中的好友
const selectedFriend = ref({
  userId: "",
  name: "",
  avatar: "",
});
// 消息输入框内容
const messageInput = ref("");
// 消息列表
const messages = ref([]);
// 搜索查询
const searchQuery = ref("");
// 过滤后的好友列表
const filteredFriends = computed(() => {
  if (!searchQuery.value.trim()) return friends.value;

  return friends.value.filter((friend) =>
    friend.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});
// 消息容器DOM引用
const messagesContainer = ref(null);
// WebSocket实例
const ws = ref(null);

// 连接WebSocket
const connectWebSocket = () => {
  // ws.value = new WebSocket(`ws://localhost:8086?userId=${currentUser.value.id}`)
  ws.value = new WebSocket(`ws://localhost:8086/imserverSingle`);

  ws.value.onopen = () => {
    console.log("WebSocket连接已建立");
    // 发送登录消息
    // sendSystemMessage("login");
  };

  ws.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log("收到消息:", data);

      handleIncomingMessage(data);

      // if (data.type === "message") {
      //   handleIncomingMessage(data.message);
      // } 
      // else if (data.type === "userList") {
      //   updateUserList(data.users);
      // }
    } catch (error) {
      console.error("解析消息失败:", error);
    }
  };

  ws.value.onclose = () => {
    console.log("WebSocket连接已关闭");
    // 5秒后尝试重新连接
    setTimeout(connectWebSocket, 5000);
  };

  ws.value.onerror = (error) => {
    console.error("WebSocket错误:", error);
  };
};

// 处理接收到的消息
const handleIncomingMessage = (message) => {
  // 校验 message 是否存在且包含 publisherId 字段
  if (!message || message.publisherId === undefined) {
    console.error('接收到的消息格式错误，缺少 publisherId 字段', message);
    return;
  }
  console.log("传入messages的数据"+JSON.stringify(message))
  messages.value.push(message);

  // 更新好友的最后一条消息
  const friendIndex = friends.value.findIndex((f) => f.userId === message.publisherId);
  if (friendIndex !== -1) {
    friends.value[friendIndex].lastMessage = message;

    // 如果不是当前选中的好友，增加未读计数
    // if (selectedFriend.value?.userId !== message.publisherId) {
    //   friends.value[friendIndex].unreadCount++;
    // }
  }

  // 滚动到底部
  scrollToBottom();
};

// 更新用户列表
const updateUserList = (users) => {
  // 这里应该更新好友列表的在线状态
  console.log("更新用户列表:", users);
};

// 发送系统消息
// const sendSystemMessage = (type, data) => {
//   if (!ws.value || ws.value.readyState !== WebSocket.OPEN) return;

//   const message = {
//     type,
//     userId: currentUser.value.id,
//     ...data,
//   };

//   ws.value.send(JSON.stringify(message));
// };

// 发送消息
const sendMessage = () => {
  if (!selectedFriend.value || !messageInput.value.trim()) return;

  const chat = {
    publisherId: currentUser.value.id,
    consumerId: selectedFriend.value.userId,
    content: messageInput.value.trim(),
    time: new Date().toISOString(),
  };

  console.log("发送的message对象"+JSON.stringify(chat))

  // 添加到消息列表
  // messages.value.push(chat);

  // 更新好友的最后一条消息（若需要可恢复相关逻辑）
  // const friendIndex = friends.value.findIndex(f => f.id === selectedFriend.value?.id)
  // if (friendIndex !== -1) {
  //   friends.value[friendIndex].lastMessage = chat
  // }

  // 通过WebSocket发送，直接发送chat对象的JSON
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(JSON.stringify(chat));
  }

  // 清空输入框
  messageInput.value = "";

  // 滚动到底部
  scrollToBottom();
};

// 选择好友
const selectFriend = (friend) => {
  if (selectedFriend.value?.userId === friend.userId) return;

  selectedFriend.value = friend;

  // 重置未读计数
  // const friendIndex = friends.value.findIndex(f => f.id === friend.id)
  // if (friendIndex !== -1) {
  //   friends.value[friendIndex].unreadCount = 0
  // }

  // 加载历史消息（实际项目中应从服务器获取）
  loadMessages(friend.userId);
};

// 加载历史消息
const loadMessages = async (friendId) => {
  try {
    console.log(
      "请求历史消息:当前用户ID=" + currentUser.value.id + ",好友ID=" + friendId
    );
    const res = await getChat(currentUser.value.id, friendId);
    // 正确判断：接口状态码为 200 且有数据（根据后端实际设计调整）
    if (res.code === 200 && res.data) {
      console.log("查询到的历史记录：", res.data);
      // 确保消息对象结构正确（包含 from、content、time 等字段）
      messages.value = res.data;
    } else {
      console.warn("接口返回非成功状态：", res.status);
      messages.value = []; // 避免 undefined 导致渲染异常
    }
  } catch (error) {
    console.error("加载历史消息失败：", error);
    messages.value = []; // 异常时清空，避免渲染错误
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

//获取所有好友
const getAllFriend = async (userId) => {
  try {
    const res = await getFollowedList(userId);
    friends.value = res.data;
    console.log("获取到的好友列表:" + JSON.stringify(res.data));
  } catch (error) {
    console.error("获取好友列表失败:", error);
  }
};
//获取用户的userId（从localStorage读取实际登录用户ID）
const getUserId = async () => {
  // 获取存储的 user 数据（JSON 字符串形式）
  const userStr = localStorage.getItem("user");
  // 解析成 JavaScript 对象
  const user = userStr ? JSON.parse(userStr) : null;
  if (user && user.userId) {
    currentUser.value.id = user.userId; // 更新为实际用户ID
    console.log("userId更新为:", currentUser.value.id);
    await getAllFriend(currentUser.value.id);
    await getUserNameAndAvatar(currentUser.value.id);
  } else {
    console.log("localStorage 中未找到有效的 user 数据,使用默认userId=3");
  }
};
//获取用户头像和姓名
const getUserNameAndAvatar = async (userId) => {
  try {
    const res = await findUserInfoByUserId(userId);
    console.log("接收到的NameAndAvatar数据", res.data);
    // 赋值表单数据
    currentUser.value.avatar = res.data.avatar;
    currentUser.value.name = res.data.name;
  } catch (error) {
    console.error("NameAndAvatar数据请求失败,请重试");
  }
};

// 生命周期钩子
onMounted(async () => {
  connectWebSocket();
  await getUserId();
});

onUnmounted(() => {
  if (ws.value) {
    ws.value.close();
  }
});

// 监听选中的好友变化
watch(selectedFriend, (newVal) => {
  if (newVal) {
    loadMessages(newVal.userId);
  } else {
    messages.value = [];
  }
});
</script>

<style scoped>
.chat-app {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background-color: #2c3e50;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-size: cover;
  background-position: center;
  position: relative;
}

.online-dot {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 10px;
  height: 10px;
  background-color: #2ecc71;
  border-radius: 50%;
  border: 2px solid white;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  border-right: 1px solid #e6e9ed;
  background-color: white;
  display: flex;
  flex-direction: column;
}

.search-box {
  padding: 12px;
  border-bottom: 1px solid #e6e9ed;
}

.search-box input {
  width: 100%;
  padding: 8px;
  border: 1px solid #e6e9ed;
  border-radius: 4px;
  outline: none;
}

.friends-list {
  flex: 1;
  overflow-y: auto;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.friend-item:hover {
  background-color: #f5f7fa;
}

.friend-item.active {
  background-color: #e6f7ff;
}

.friend-info {
  flex: 1;
  margin-left: 12px;
  min-width: 0;
}

.name {
  font-weight: 500;
  margin-bottom: 4px;
}

.last-message {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #888;
  font-size: 12px;
}

.last-message span:first-child {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}

.time {
  margin-left: 8px;
}

.unread-count {
  background-color: #e74c3c;
  color: white;
  font-size: 12px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #e6e9ed;
  background-color: white;
}

.back-btn {
  display: none;
  padding: 8px;
  cursor: pointer;
}

.friend-info {
  margin-left: 12px;
}

.status {
  font-size: 12px;
  color: #888;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f7fa;
}

.message-list {
  display: flex;
  flex-direction: column;
}

.message {
  max-width: 70%;
  margin-bottom: 16px;
}

.message.incoming {
  align-self: flex-start;
}

.message.outgoing {
  align-self: flex-end;
}

.message-content {
  padding: 8px 12px;
  border-radius: 8px;
}

.message.incoming .message-content {
  background-color: white;
  border: 1px solid #e6e9ed;
}

.message.outgoing .message-content {
  background-color: #1890ff;
  color: white;
}

.time {
  font-size: 12px;
  color: #888;
  margin-top: 4px;
  text-align: right;
}

.message.outgoing .time {
  color: rgba(255, 255, 255, 0.7);
}

.input-area {
  display: flex;
  padding: 12px;
  border-top: 1px solid #e6e9ed;
  background-color: white;
}

.input-area input {
  flex: 1;
  padding: 8px;
  border: 1px solid #e6e9ed;
  border-radius: 4px;
  margin-right: 8px;
  outline: none;
}

.input-area button {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.input-area button:hover {
  background-color: #40a9ff;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

@media (max-width: 768px) {
  .sidebar {
    width: 100%;
    display: block;
  }

  .chat-window {
    display: none;
  }

  .chat-window.active {
    display: flex;
  }

  .back-btn {
    display: block;
  }
}
</style>
